<?php
/**
 * 数据同步LOG
 *
 * User: kaikaic
 * Date: 2018/11/15
 * Time: 23:23
 */

namespace app\exam\service;

use service\BasicService;
use think\Db;

/**
 * 接口数据规则:返回json数组，{code,data,msg}
 *
 * code=200:正常,其他:错误
 * data,实际数据
 * msg,信息提示
 */

class SyncService extends BasicService {

    const TYPE_FAILED_UPDATE = "failed_update";

    const TYPE_FAILED_INSERT = "failed_insert";

    const TYPE_INSERT = "insert";

    const TYPE_UPDATE = "update";

    public function init() {
        $this->dataTable = ['ExamSyncLog'];
    }

    /**
     * error=失败
     * update=更新记录数
     * failed=操作失败记录数
     * insert=新增记录数
     * closed=关闭记录数
     * total=总记录数
     */
    public function updateMec($dataArray) {
        $result = array(
            'error'=>0, 'update'=>0, 'failed'=>0, 'insert'=>0, 'close'=>0, 'total'=>0
        );

        if (!$this->checkResponse($dataArray)) {
            $result['error'] = 1;
            return $result;
        }

        $records = $dataArray['data'];
        $size = count($records);
        $result['total'] = $size;

        /* step1:完成新数据写入，已有数据更新 */
        $uniqueCodeArray = array();
        for ($i=0; $i<$size; $i++) {
            $record = $records[$i];

            $uniqueCode = trim($record['unique_code']);
            if (!$uniqueCode) {
                continue;
            }
            $uniqueCodeArray[] = $uniqueCode;

            $mec = MecService::getInstance()->single(array('unique_code'=>$uniqueCode));
            if ($mec) {
                $rs = $this->doUpdateMec($record, $mec);
                if ($rs) {
                    $result['update']++;
                }else {
                    $result['failed']++;
                }
            }else {
                $rs = $this->doInsertMec($record);
                if ($rs) {
                    $result['insert']++;
                }else {
                    $result['failed']++;
                }
            }
        }

        /* step2:数据库已有，接口里没有，标识体检中心已停用，修改状态=已停用 */
        $mecList = MecService::getInstance()->select(array());
        $mecUniqueCodes = array();
        for ($i=0; $i<count($mecList); $i++) {
            $mecUniqueCodes[] = $mecList[$i]['unique_code'];
        }

        echo "step2";

        // 剩余的记录
        $closeMec = array_diff($mecUniqueCodes, $uniqueCodeArray);
        print_r($closeMec);exit;

        for ($i=0; $i<count($closeMec); $i++) {
            $rs = $this->doClosetMec($closeMec[$i]);
            if ($rs) {
                $result['update']++;
            }else {
                $result['failed']++;
            }
        }

        print_r($result);

        exit;

        return $result;
    }

    private function doClosetMec($uniqueCode) {
        $update = array();
        $update['status'] = 2;
        //TODO 其他数据

        $rs = MecService::getInstance()->update($update, $uniqueCode, "unique_code");
        if (!$rs) {
            // 记录错误数据
            $logArray = array();
            $logArray['type'] = self::TYPE_FAILED_UPDATE;

            $update['unique_code'] = $uniqueCode;
            $logArray['data'] = serialize($update);
            $logArray['create_time'] = time();
            $this->insert($logArray);

            return false;
        }

        return true;
    }

    private function doInsertMec($record) {
        $params = array();
        $params['name'] = $record['name'];
        $params['unique_code'] = $record['unique_code'];
        $params['logo'] = $record['logo'];
        $params['category_id'] = $record['category_id'];
        $params['province_id'] = $record['province_id'];
        $params['city_id'] = $record['city_id'];
        $params['district_id'] = $record['district_id'];
        $params['address'] = $record['address'];
        $params['phone'] = $record['phone'];
        $params['intro'] = $record['intro'];
        $params['sort'] = MecService::getInstance()->getMaxSort() + 1;
        $params['status'] = 1;
        $params['create_time'] = time();

        $rs = MecService::getInstance()->insert($params);
        if (!$rs) {
            // 记录错误数据
            $logArray = array();
            $logArray['type'] = self::TYPE_FAILED_INSERT;

            $logArray['data'] = serialize($params);
            $logArray['create_time'] = time();
            $this->insert($logArray);

            return false;
        }

        return true;
    }

    private function doUpdateMec($record, $mec) {
        $update = array();
        $update['unique_code'] = $record['unique_code'];
        $update['logo'] = $record['logo'];
        $update['category_id'] = $record['category_id'];
        $update['province_id'] = $record['province_id'];
        $update['city_id'] = $record['city_id'];
        $update['district_id'] = $record['district_id'];
        $update['address'] = $record['address'];
        $update['phone'] = $record['phone'];
        $update['intro'] = $record['intro'];

        $update['status'] = 1;

        //TODO 其他数据

        $rs = MecService::getInstance()->update($update, $mec['id']);
        if (!$rs) {
            // 记录错误数据
            $logArray = array();
            $logArray['type'] = self::TYPE_FAILED_UPDATE;

            $update['id'] = $mec['id'];
            $logArray['data'] = serialize($update);
            $logArray['create_time'] = time();
            $this->insert($logArray);

            return false;
        }

        return true;
    }

    public function updateMecSet($dataArray) {
        $result = array(
            'error'=>0, 'update'=>0, 'failed'=>0, 'insert'=>0
        );

        if (!$this->checkResponse($dataArray)) {
            $result['error'] = 1;
            return $result;
        }
    }

    /**
     * 返回数据是否正常
     */
    private function checkResponse($response) {
        if (!is_array($response)) {
            return false;
        }

        if (!isset($response['data']) || !$response['data']) {
            return false;
        }

        return true;
    }
}